import { GameMode } from "@minecraft/server";
import { RegionEventType } from "@sapi-game/gameEvent/events/regionEvents";
import { Game, GameComponent } from "@sapi-game/main";
import { EffectIds } from "@sapi-game/utils/vanila-data";
import { pixelPartyPlayer } from "../module";
import { PixelPartyMainState } from "../states/mainState";
import { Duration } from "@sapi-game/utils";
import { InfoScoreboard } from "@sapi-game/gameComponent/view/infoScoreboard";

export class PixelPartyDaemon extends GameComponent<PixelPartyMainState> {
    override onAttach(): void {
        this.subscribe(Game.events.interval, () => {
            this.context.players.forEach((p) => {
                p.player.addEffect(EffectIds.Resistance, 50, {
                    amplifier: 100,
                    showParticles: false,
                });
                p.player.addEffect(EffectIds.FireResistance, 50, {
                    showParticles: false,
                });
            });
        });
        //离开区域视为死亡
        this.subscribe(
            Game.events.region,
            (t) => {
                if (t.type == RegionEventType.Leave) {
                    const gamePlayer = this.context.players.getById(
                        t.player.id
                    );
                    if (gamePlayer && gamePlayer.alive) {
                        this.handleDie(gamePlayer);
                    }
                }
            },
            this.context.map.gameRegion
        );
        this.subscribe(
            Game.events.interval,
            () => {
                this.updateScore();
                //检测结束
                this.checkEnd();
            },
            new Duration(10)
        );
    }

    handleDie(player: pixelPartyPlayer) {
        player.alive = false;
        if (!player.player) return;
        player.player.dimension.spawnEntity(
            "minecraft:lightning_bolt",
            player.player.location
        );
        player.player.setGameMode(GameMode.Spectator);
        player.player.teleport(this.context.map.spawnPoint);
        this.context.players.sendMessage(`§c§l${player.name}被淘汰出局`);
    }

    updateScore() {
        let liveCnt = 0;
        let WatchingCnt = 0;
        this.context.players.forEach((p) => {
            if (p.alive) {
                liveCnt++;
            } else {
                WatchingCnt++;
            }
        });
        const info = this.state.getComponent(InfoScoreboard);
        info.updateLines([
            "",
            `当前轮次: §e${this.context.round}`,
            `剩余玩家: §b${liveCnt}`,
            "",
            `观战: §s${WatchingCnt}`,
            "",
        ]);
    }

    checkEnd() {
        const liveCnt = this.context.players.filter(
            (p) => p.isValid && p.alive
        ).length;
        if (liveCnt <= 1) {
            this.state.end();
        }
    }
}
